﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;
using BLL;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using ICSharpCode.SharpZipLib.Zip;
using Model;

public partial class ViewbyProduct_DKKELectronicsList_DKKProductSNCategory : System.Web.UI.Page
{
    private TestItem ti;
    private Random ran;
    private string productSN, tempandhum, productionM;
    private string testingD;

    public ViewbyProduct_DKKELectronicsList_DKKProductSNCategory()
    {
        ti = new TestItem();
        ran = new Random();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            this.Button6.Attributes.Add("onclick", "PasteData()");
        }
        //Text2 for ProductSN,Text8 for Temperature humidity
        this.CrystalReportViewer1.Visible = false;
        this.Page.Unload += new EventHandler(Page_Unload);
    }

    void Page_Unload(object sender, EventArgs e)
    {
        this.CrystalReportSource1.Dispose();
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        BindVar();
        ForCrystalReport(productSN, tempandhum, productionM);
    }

    protected void BindVar()
    {
        productSN = this.TextBox1.Text.Trim();
        tempandhum = this.TextBox2.Text.Trim();
        productionM = this.TextBox4.Text.Trim();
        testingD = ran.Next(8, 30).ToString() + "/" + productionM.Substring(5, 2) + "/" + productionM.Substring(0, 4);
    }

    protected void ForCrystalReport(string productSN, string tempandhum, string productionM)
    {
        CrystalReportSource1.ReportDocument.Load(Server.MapPath("ViewDKKTestItem.rpt"));

        TextObject txtProductSN = (TextObject)this.CrystalReportSource1.ReportDocument.ReportDefinition.ReportObjects["Text2"];
        txtProductSN.Text = productSN;
        TextObject txtTempandHum = (TextObject)this.CrystalReportSource1.ReportDocument.ReportDefinition.ReportObjects["Text8"];
        txtTempandHum.Text = tempandhum;
        TextObject txtProductionM = (TextObject)this.CrystalReportSource1.ReportDocument.ReportDefinition.ReportObjects["Text7"];
        txtProductionM.Text = productionM;
        TextObject txtTestingD = (TextObject)this.CrystalReportSource1.ReportDocument.ReportDefinition.ReportObjects["Text6"];
        txtTestingD.Text = testingD;

        DKKTestItemInfo dti = ti.GetDKKTestItembySN(productSN);
        if (string.IsNullOrEmpty(dti.ProductSN))
        {
            string str = "没有" + productSN + "的测试数据";
            ClientScript.RegisterStartupScript(ClientScript.GetType(), "", "<script>alert('" + str + "');</script>");
            return;
        }
        else
        {
            IList<DKKTestItemInfo> list = new List<DKKTestItemInfo>();
            list.Add(dti);
            CrystalReportSource1.ReportDocument.SetDataSource(list);
            CrystalReportSource1.DataBind();
            this.CrystalReportViewer1.ReportSource = CrystalReportSource1;
            CrystalReportViewer1.DataBind();
            this.CrystalReportViewer1.Visible = true;
        }
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        BindVar();
        //ForCrystalReport(productSN, tempandhum);
        string ReportFile = Server.MapPath("ViewDKKTestItem.rpt");
        string ExcelFileName = Server.MapPath("~/ZedGraphImages/DKKSParamTestData.pdf");
        if (!ExportToExcel(ReportFile, ExcelFileName))
        {
            string str = "没有" + productSN + "的测试数据，或报表导出出现问题！";
            ClientScript.RegisterStartupScript(ClientScript.GetType(), "", "<script>alert('" + str + "');</script>");
        }
    }

    public bool ExportToExcel(string ReportFile, string ExcelFileName)
    {
        try
        {
            ReportDocument ReportDOC = new ReportDocument();
            DiskFileDestinationOptions FileOPS = new DiskFileDestinationOptions();
            ExportOptions ExOPS;
            ReportDOC.Load(ReportFile);

            DKKTestItemInfo dti = ti.GetDKKTestItembySN(productSN);
            if (string.IsNullOrEmpty(dti.ProductSN))
            {
                throw new Exception("没有相应测试数据!");
            }
            else
            {
                TextObject txtProductSN = (TextObject)ReportDOC.ReportDefinition.ReportObjects["Text2"];
                txtProductSN.Text = productSN;
                TextObject txtTempandHum = (TextObject)ReportDOC.ReportDefinition.ReportObjects["Text8"];
                txtTempandHum.Text = tempandhum;
                TextObject txtProductionM = (TextObject)ReportDOC.ReportDefinition.ReportObjects["Text7"];
                txtProductionM.Text = productionM;
                TextObject txtTestingD = (TextObject)ReportDOC.ReportDefinition.ReportObjects["Text6"];
                txtTestingD.Text = testingD;
                IList<DKKTestItemInfo> list = new List<DKKTestItemInfo>();
                list.Add(dti);
                ReportDOC.SetDataSource(list);

                FileOPS.DiskFileName = ExcelFileName;
                ExOPS = ReportDOC.ExportOptions;
                ExOPS.DestinationOptions = FileOPS;
                ExOPS.ExportDestinationType = CrystalDecisions.Shared.ExportDestinationType.DiskFile;
                ExOPS.ExportFormatType = CrystalDecisions.Shared.ExportFormatType.PortableDocFormat;
                ReportDOC.Export();
                Response.Clear();
                Response.Buffer = true;
                EnableViewState = false;
                string filename = productSN + ".pdf";
                Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(filename, Encoding.UTF8));
                Response.WriteFile(ExcelFileName);
                Response.Flush();
                Response.End();
                Response.Close();
                return true;
            }
        }
        catch
        {
            return false;
        }
    }

    protected void Button5_Click(object sender, EventArgs e)
    {
        string str = this.myVal.Value;
        string[] strs = str.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
        foreach (string st in strs)
        {
            if (!ProductSNCompare(st))
                this.ListBox1.Items.Add(st.Trim());
        }
        this.Label1.Text = this.ListBox1.Items.Count.ToString();
    }

    protected void Button3_Click(object sender, EventArgs e)
    {
        this.ListBox1.Items.Clear();
        this.Label1.Text = this.ListBox1.Items.Count.ToString();
    }

    protected bool ProductSNCompare(string psn)
    {
        foreach (ListItem item in this.ListBox1.Items)
        {
            if (item.Text == psn)
            {
                return true;
            }
        }
        return false;
    }

    public bool ExportToExcel1(string ReportFile, string ExcelFileName)
    {
        try
        {
            ReportDocument ReportDOC = new ReportDocument();
            DiskFileDestinationOptions FileOPS = new DiskFileDestinationOptions();
            ExportOptions ExOPS;
            ReportDOC.Load(ReportFile);

            DKKTestItemInfo dti = ti.GetDKKTestItembySN(productSN);
            if (string.IsNullOrEmpty(dti.ProductSN))
            {
                throw new Exception("没有相应测试数据!");
            }
            else
            {
                TextObject txtProductSN = (TextObject)ReportDOC.ReportDefinition.ReportObjects["Text2"];
                txtProductSN.Text = productSN;
                TextObject txtTempandHum = (TextObject)ReportDOC.ReportDefinition.ReportObjects["Text8"];
                txtTempandHum.Text = tempandhum;
                TextObject txtProductionM = (TextObject)ReportDOC.ReportDefinition.ReportObjects["Text7"];
                txtProductionM.Text = productionM;
                TextObject txtTestingD = (TextObject)ReportDOC.ReportDefinition.ReportObjects["Text6"];
                txtTestingD.Text = testingD;
                IList<DKKTestItemInfo> list = new List<DKKTestItemInfo>();
                list.Add(dti);
                ReportDOC.SetDataSource(list);

                FileOPS.DiskFileName = ExcelFileName;
                ExOPS = ReportDOC.ExportOptions;
                ExOPS.DestinationOptions = FileOPS;
                ExOPS.ExportDestinationType = CrystalDecisions.Shared.ExportDestinationType.DiskFile;
                ExOPS.ExportFormatType = CrystalDecisions.Shared.ExportFormatType.PortableDocFormat;
                ReportDOC.Export();
                return true;
            }
        }
        catch
        {
            return false;
        }
    }

    protected void Button6_Click(object sender, EventArgs e)
    {
        if (this.ListBox1.Items.Count == 0 || this.ListBox1.Items.Count > 50)
        {
            string str = "请保证产品序列号数量大于0且小于50！";
            ClientScript.RegisterStartupScript(ClientScript.GetType(), "", "<script>alert('" + str + "');</script>");
            return;
        }
        StringBuilder sbFail = new StringBuilder();
        List<string> strPass = new List<string>();
        foreach (ListItem item in this.ListBox1.Items)
        {
            productSN = item.Text;
            tempandhum = this.TextBox3.Text.Trim();
            productionM = this.TextBox5.Text.Trim();
            testingD = ran.Next(8, 30).ToString() + "/" + productionM.Substring(5, 2) + "/" + productionM.Substring(0, 4);
            string ReportFile = Server.MapPath("ViewDKKTestItem.rpt");
            string ExcelFileName = Server.MapPath("~/ZedGraphImages/" + productSN + ".pdf");
            if (!ExportToExcel1(ReportFile, ExcelFileName))
            {
                sbFail.Append(productSN);
                sbFail.Append(',');
            }
            else
            {
                strPass.Add(productSN);
            }
        }
        if (sbFail.Length > 0)
        {
            string str = sbFail.ToString();
            str = str.TrimEnd(',');
            str = "以下产品序列号没有测试数据，或测试数据没有正确导出：" + str;
            ClientScript.RegisterStartupScript(ClientScript.GetType(), "", "<script>alert('" + str + "');</script>");
            return;
        }
        if (strPass.Count > 0)
        {
            string directoryName = string.Format("{0:yyyyMMddHHmmssffff}", DateTime.Now);
            string directoryPath = Server.MapPath("~/ZedGraphImages/" + directoryName);
            string targetZipFile = Server.MapPath("~/ZedGraphImages/" + directoryName + ".zip");
            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }
            foreach (string str in strPass)
            {
                File.Move(Server.MapPath("~/ZedGraphImages/" + str + ".pdf"), directoryPath + "\\" + str + ".pdf");
            }

            SharpZipLibHelper ziphelper = new SharpZipLibHelper();
            ziphelper.ZipFileOrFolder(directoryPath, true, targetZipFile);
            Directory.Delete(directoryPath, true);

            Response.ContentType = "application/x-zip-compressed";
            Response.AddHeader("Content-Disposition", "attachment;filename=DKKSParamTestData.zip");
            string filename = targetZipFile;
            Response.TransmitFile(filename);
        }
    }
}


public class MyNameTransfom : ICSharpCode.SharpZipLib.Core.INameTransform
{

    #region INameTransform 成员

    public string TransformDirectory(string name)
    {
        return null;
    }

    public string TransformFile(string name)
    {
        return Path.GetFileName(name);
    }

    #endregion
}

public class StreamStaticDataSource : IStaticDataSource
{
    private Stream _stream;

    public StreamStaticDataSource(Stream stream)
    {
        _stream = stream;
    }

    #region IStaticDataSource Members

    public Stream GetSource()
    {
        return _stream;
    }

    #endregion
}
